package com.example.myprojectoffeixue;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.localization.FristActivity;

import android.os.Handler.Callback;

import org.apache.http.entity.StringEntity;

import android.widget.LinearLayout.LayoutParams;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends Activity implements Callback {
    public EditText Et_Username;
    public EditText Et_Password;
    //public boolean flag;
    MyApplication Myapp;
    public boolean isclose;//udp是否关闭标志位；
    PackageInfo pi;
    String forceUpdate;
    GateWay Gw2;
    String desc;
    String k;
    String code;
    // PopupWindow对象
    private PopupWindow selectPopupWindow = null;
    // 自定义Adapter
    private OptionsAdapter optionsAdapter = null;
    // 下拉框选项数据源
    private List<String> datas;
    // 下拉框依附附件
    private LinearLayout parent;
    // 下拉框依附组件宽度，也将作为下拉框的宽度
    private int pwidth;
    // 文本框
    // 下拉箭头图片组件
    private ImageView image;
    // 展示所有下拉选项的listView
    private ListView listView = null;
    // 用来处理选中或者删除下拉项消息
    private Handler handler;
    // 是否初始化完成标志
    private boolean flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_login);
        update();
        init();
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        while (!flag) {
            initWedget();
            flag = true;
        }
    }

    /**
     * 初始化界面
     */
    private void initWedget() {
        image = (ImageView) findViewById(R.id.btn_select);
        handler = new Handler(LoginActivity.this);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (flag) {
                    PopupWindowShowing();
                }

            }
        });
        initPopupWindow();
    }

    /**
     * 初始化下拉框
     */
    @SuppressWarnings("deprecation")
    private void initPopupWindow() {
        datas = initDatas();
        parent = (LinearLayout) findViewById(R.id.account);
        View loginwindow = (View) this.getLayoutInflater().inflate(R.layout.options, null);
        listView = (ListView) loginwindow.findViewById(R.id.list);
        optionsAdapter = new OptionsAdapter(this, handler, datas);
        listView.setAdapter(optionsAdapter);
        int width = parent.getWidth();
        pwidth = width;
        selectPopupWindow = new PopupWindow(loginwindow, pwidth, LayoutParams.WRAP_CONTENT, true);
        selectPopupWindow.setOutsideTouchable(true);
        selectPopupWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    protected void PopupWindowShowing() {
        selectPopupWindow.showAsDropDown(parent, 3, -3);
    }

    /**
     * 下拉框数据
     *
     * @return
     */
    private List<String> initDatas() {
        Set set = new HashSet();
        SharedPreferences sp2 = getSharedPreferences("data", Context.MODE_PRIVATE);
        HashSet<String> str_set = (HashSet<String>) sp2.getStringSet("data", set);
        Iterator<String> it = str_set.iterator();
        List<String> listItems = new ArrayList<String>();
        while (it.hasNext()) {
            String str = it.next();
            Log.d("data", str);
            listItems.add(str);
        }
        return listItems;
    }

    @Override
    public boolean handleMessage(Message message) {
        Bundle data = message.getData();
        switch (message.what) {
            case 1:
                int selIndex = data.getInt("selIndex");
                Et_Username.setText(datas.get(selIndex));
                dismiss();
                break;
        }
        return false;
    }


    @Override
    protected void onStart() {
        isclose=true;
        super.onStart();
    }

    private void dismiss() {
        selectPopupWindow.dismiss();
    }

    private void init() {
        Myapp = (MyApplication) getApplication();
        Et_Username = (EditText) findViewById(R.id.et_login);
        Et_Password = (EditText) findViewById(R.id.et1_login);
        TextView tv = (TextView) findViewById(R.id.wangji);
        SharedPreferences sp = getSharedPreferences("first", MODE_PRIVATE);
        String username = sp.getString("username", null);
        String password = sp.getString("password", null);
        if (username != null) {
            Et_Username.setText(username);
            Et_Password.setText(password);
        }
        tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent it = new Intent(LoginActivity.this, WangJiMMActivity.class);
                startActivity(it);
            }
        });
    }

    public void click(final View v) {
        if ("".equals(Et_Username.getText().toString())) {
            HttpConnection.showToast(getBaseContext(), "请输入手机号");
        } else if ("".equals(Et_Password.getText().toString())) {
            HttpConnection.showToast(getBaseContext(), "请输入密码");
        } else {
            UserClass Uc = new UserClass();
            Uc.mobile = Et_Username.getText().toString();
            Uc.password = Et_Password.getText().toString();
            Uc.os = "Android";
            String js = JSON.toJSONString(Uc);
            js = AESUtil.encrypt(js);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setContentType("application/json");
            try {
                params.setBodyEntity(new StringEntity(js, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/user/login", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            HttpConnection.toastLog("网络错误", LoginActivity.this);
                            Log.d("exception",arg0.toString()+"--"+arg1);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {


                            if (arg0.result != null && !("".equals(arg0.result))) {
                                String decode = null;
                                decode = AESUtil.decrypt(arg0.result);
                                Log.d("decode",decode);
                                Gw2 = JSON.parseObject(decode, GateWay.class);
                                if (0 == Gw2.status) {
                                    Myapp.username = Et_Username.getText().toString();
                                    Myapp.authId = Gw2.authId;
                                    Myapp.userId = Gw2.userId;
                                    Myapp.authToken = Gw2.authToken;
                                    SharedPreferences sp2 = getSharedPreferences("data", Context.MODE_PRIVATE);
                                    Set set = new HashSet();
                                    HashSet<String> str_set = (HashSet<String>) sp2.getStringSet("data", set);
                                    SharedPreferences.Editor et = sp2.edit();
                                    str_set.add(Et_Username.getText().toString());
                                    et.putStringSet("data", str_set);
                                    et.commit();

                                    if(Gw2.regId==null||"".equals(Gw2.regId)){
                                        updateJpush();
                                    }
                                    GetDeviceList();
                                } else {
                                    HttpConnection.toastLog(Gw2.msg, LoginActivity.this);
                                }

                            }
                        }
                    });
        }
    }

    public void regin(View v) {
        Intent it = new Intent(LoginActivity.this, ReginActivity.class);
        startActivity(it);
    }


    public void update() {

        PackageManager pm = getPackageManager();

        try {
            pi = pm.getPackageInfo(getPackageName(), 0);
        } catch (Exception e) {
        }

        int versionCode = pi.versionCode;
        //int versionCode=0;
        String os = "Android";
        Websocketutil ws = new Websocketutil(os, versionCode);
        String j = JSON.toJSONString(ws);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/user/updateApp", params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                if (arg0.result != null && !("".equals(arg0.result))) {

                    arg0.result = AESUtil.decrypt(arg0.result);
                    JSONObject j = JSONObject.parseObject(arg0.result);
                    String status = j.getString("status");
                    if ("0".equals(status)) {
                        JSONObject j1 = j.getJSONObject("latestVersion");
                        if (j1 != null) {
                            k = j1.getString("url");
                            forceUpdate = j1.getString("forceUpdate");
                            desc = j1.getString("desc");
                        }
                        if (k != null) {
                            UpdateApp u = new UpdateApp(LoginActivity.this, k);
                            u.updateMsg = desc;
                            u.checkUpdateInfo();
                        }

                    } else {
                        HttpConnection.toastLog("服务器错误", LoginActivity.this);
                    }
                } else {
                    HttpConnection.toastLog("服务器错误", LoginActivity.this);
                }
            }
        });
    }
    private void GetDeviceList() {
        if (Et_Username.getText().toString() != null) {
            UserClass Gw = new UserClass();
            Gw.userId = Myapp.userId;
            Gw.status = 1;
            String j = JSON.toJSONString(Gw);
            Log.d("ffff", j);
            j = AESUtil.encrypt(j);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setHeader("Content-Type", "application/json");
            try {
                params.setBodyEntity(new StringEntity(j, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/getDeviceList", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            HttpConnection.toastLog("网络异常", LoginActivity.this);

                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            Log.d("arg0", arg0.result);
                            if (arg0.result != null && !("".equals(arg0.result))) {
                                arg0.result = AESUtil.decrypt(arg0.result);
                                Log.d("result", arg0.result);
                                JSONObject jb = JSONObject.parseObject(arg0.result);
                                String status = jb.getString("status");
                                if ("0".equals(status)) {
                                    SharedPreferences sp = getSharedPreferences("first", MODE_PRIVATE);
                                    sp.edit().putString("username", Et_Username.getText().toString()).commit();
                                    sp.edit().putString("password", Et_Password.getText().toString()).commit();
                                    sp.edit().putString("UserId", Gw2.userId).commit();
                                    sp.edit().putString("authToken", Gw2.authToken).commit();
                                    sp.edit().putString("authId", Gw2.authId).commit();
                                    sp.edit().putBoolean("isexit", false).commit();
                                    JSONArray ja = jb.getJSONArray("deviceList");
                                    sp.edit().putString("deviceList",ja.toString()).commit();
                                    Myapp.m_gateway = (ArrayList<GateWay>) JSON.parseArray(ja.toString(), GateWay.class);
                                    MyApplication.localflag=false;
                                    isclose=false;
                                    Intent it = new Intent(LoginActivity.this,MainActivity.class);
                                    startActivity(it);
                                    finish();
                                } else {
                                    HttpConnection.toastLog("服务器错误", LoginActivity.this);
                                }
                            } else {
                                HttpConnection.toastLog("服务器错误", LoginActivity.this);
                            }
                        }

                    });
        }
    }

    public void updateJpush(){
        GateWay gw=new GateWay();
        gw.userId=Myapp.userId;
        gw.regId= JPushInterface.getRegistrationID(getBaseContext());
        String j = JSON.toJSONString(gw);
        j = AESUtil.encrypt(j);
        Log.d("j",j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.updateJpush, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        HttpConnection.toastLog("网络异常", LoginActivity.this);

                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                     Log.d("retyu",arg0.result);
                    }
                });

    }


    @Override
    protected void onDestroy() {

        Log.d("close22222","close33333"+MyApplication.localflag);
        if(Myapp.udp!=null&&isclose){
            Log.d("close1111","close2222");
            Myapp.udp.close();
        }
        super.onDestroy();
    }
}
